package com.itdianzi.service.cargo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itdianzi.dao.cargo.ContractDao;
import com.itdianzi.dao.cargo.ContractProductDao;
import com.itdianzi.dao.cargo.ExtCproductDao;
import com.itdianzi.dao.export.ExportDao;
import com.itdianzi.dao.export.ExportProductDao;
import com.itdianzi.dao.export.ExtEproductDao;
import com.itdianzi.domain.cargo.*;
import com.itdianzi.domain.export.Export;
import com.itdianzi.domain.export.ExportExample;
import com.itdianzi.domain.export.ExportProduct;
import com.itdianzi.domain.export.ExtEproduct;
import com.itdianzi.domain.vo.ExportProductResult;
import com.itdianzi.domain.vo.ExportResult;
import com.itdianzi.service.cargo.ExportService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Array;
import java.util.*;

@Service
public class ExportServiceImpl implements ExportService {
    @Autowired
    private ExportDao exportDao;
    @Override
    public Export findById(String id) {
        return exportDao.selectByPrimaryKey(id);
    }


    @Autowired
    private ContractDao contractDao;//合同dao
    @Autowired
    private ContractProductDao contractProductDao;//货物dao
    @Autowired
    private ExportProductDao exportProductDao;//报运货物dao
    @Autowired
    private ExtCproductDao extCproductDao;//附件dao
    @Autowired
    private ExtEproductDao extEproductDao;//报运下附件的dao
    /**
     * 新增出口报运单
     * 1.将合同数据转换成出口报运单数据
     * 2.将货物数据转换成出口货物数据
     * 3.将附件数据转换出口附件的数据
     * @param export
     */
    @Override
    public void save(Export export) {//只有用户输入的数据
        //1.将合同数据转换成出口报运单数据
        export.setId(UUID.randomUUID().toString());
        //制单日期
        export.setInputDate(new Date());
        //拼接一个合同确认书号，有多少合同
        String customerContract = "";
        //先查询合同对象   获得合同id 查询合同对象
        String contractIds = export.getContractIds();
        String[] contractIdsSplit = contractIds.split(",");//获得报运的合同id
        //select * from 表 where id = 1   select * from 表 where id in (1,2,3)
        ContractExample contractExample = new ContractExample();
        ContractExample.Criteria contractExampleCriteria = contractExample.createCriteria();
        //asList将数组转换成list集合
        contractExampleCriteria.andIdIn(Arrays.asList(contractIdsSplit));
        List<Contract> contracts = contractDao.selectByExample(contractExample);

        //遍历合同数据
        for (Contract contract : contracts) {
            customerContract += contract.getContractNo() + " ";//拼接合同的号
            //需要修改合同的状态值  将state修改为2
            contract.setState(2);
            contractDao.updateByPrimaryKeySelective(contract);//修改合同状态
        }
        //新增的出口报运单状态
        export.setState(0);//草稿状态
        //拼接好的确认书号
        export.setCustomerContract(customerContract);



        //2.将货物数据转换成出口货物数据
        //查询每个合同下的货物数据，根据合同id的数组直接查询
        ContractProductExample contractProductExample = new ContractProductExample();
        ContractProductExample.Criteria contractProductExampleCriteria = contractProductExample.createCriteria();
        contractProductExampleCriteria.andContractIdIn(Arrays.asList(contractIdsSplit));//根据数组查询到所有的货物
        List<ContractProduct> contractProducts = contractProductDao.selectByExample(contractProductExample);

        //储存id对应关系
        Map<String, String> idMap = new HashMap<>();
        //转换成出口报运货物数据
        for (ContractProduct contractProduct : contractProducts) {
            //出口报运的货物对象
            ExportProduct exportProduct = new ExportProduct();
            //对象转换   参数1  源对象   参数2  目标对象
            //将源对象的数据复制到目标对象中  前提是字段名称一致，字段名称不一致，不动
            BeanUtils.copyProperties(contractProduct, exportProduct);

            //赋值Id
            exportProduct.setId(UUID.randomUUID().toString());
            //需要在赋值数据完成以后添加
            exportProduct.setExportId(export.getId());//添加报运单id
            //export对象必须提前设置id

            //key 是以前的id  value是新的id
            idMap.put(contractProduct.getId(), exportProduct.getId());
            //保存数据
            exportProductDao.insertSelective(exportProduct);

        }



        //3.将附件数据转换成出口附件的数据
        //根据购销合同的id查询附件的数据（以前有冗余字段）
        ExtCproductExample extCproductExample = new ExtCproductExample();
        ExtCproductExample.Criteria extCproductExampleCriteria = extCproductExample.createCriteria();
        extCproductExampleCriteria.andContractIdIn(Arrays.asList(contractIdsSplit));
        List<ExtCproduct> extCproducts = extCproductDao.selectByExample(extCproductExample);

        //附件对象
        //遍历
        for (ExtCproduct extCproduct : extCproducts) {
            //将附件数据转换成报运附件的数据
            ExtEproduct extEproduct = new ExtEproduct();
            BeanUtils.copyProperties(extCproduct, extEproduct);
            //重新复制Id
            extEproduct.setId(UUID.randomUUID().toString());
            //保存数据---必须建立联系
            extEproduct.setExportId(export.getId());//报运单的id

            //根据以前的货物id 获得新的报运货物id
            String exportProductId = idMap.get(extCproduct.getContractProductId());
            extEproduct.setExportProductId(exportProductId);//报运货物的Id
            //保存附件对象
            extEproductDao.insertSelective(extEproduct);

        }

        //保存报运单对象
        //设置货物数量 和 附件数量
        export.setProNum(contractProducts.size());
        export.setExtNum(extCproducts.size());
        //保存对象
        exportDao.insertSelective(export);
    }

    /**
     * 修改报运单 及 报运单货物数据
     * @param export
     */
    @Override
    public void update(Export export) {
        //修改报运单
        exportDao.updateByPrimaryKeySelective(export);
        //修改报运单下货物数据
        if (export.getExportProducts()!=null && !export.getExportProducts().isEmpty()) {
            for (ExportProduct exportProduct : export.getExportProducts()) {
                exportProductDao.updateByPrimaryKeySelective(exportProduct);
            }
        }


    }

    @Override
    public void delete(String id) {
        Export export = exportDao.selectByPrimaryKey(id);
        //删除报运单
        exportDao.deleteByPrimaryKey(id);
        //获取购销合同ID
        System.out.println(export);


        String contractIds = export.getContractIds();

        String[] split = contractIds.split(",");
        for (String s : split) {
        //根据购销合同ID得到合同数据
        Contract contract = contractDao.selectByPrimaryKey(contractIds);
        contract.setState(0);//将State改为0
        //保存修改后的合同数据
        contractDao.updateByPrimaryKeySelective(contract);

        }

    }

    @Override
    public PageInfo findAll(ExportExample example, int page, int size) {
        PageHelper.startPage(page, size);
        List<Export> exports = exportDao.selectByExample(example);

        return new PageInfo(exports);
    }

    @Override
    public void updateExport(ExportResult exportResult) {
        //修改报运单的状态
        Export export = new Export();
        export.setId(exportResult.getExportId());//id
        export.setRemark(exportResult.getRemark());//报运信息
        export.setState(exportResult.getState());//将状态修改为2
        exportDao.updateByPrimaryKeySelective(export);

        //修改报运单下每个货物的税务金额
        for (ExportProductResult exportProductResult : exportResult.getProducts()) {
            //创建对象
            ExportProduct exportProduct = new ExportProduct();
            exportProduct.setId(exportProductResult.getExportProductId());//赋值id
            exportProduct.setTax(exportProductResult.getTax());//税务金额

            //修改报运单货物数据
            exportProductDao.updateByPrimaryKeySelective(exportProduct);
        }
    }
}
